<template>
    <div>
        <van-nav-bar title="我的地址" left-text="返回" left-arrow @click-left="$router.back()" />
        <van-skeleton title :row="12" v-show="isLoading" />
        <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit"
            v-show="!isLoading" @select="changeDefaultAddress" />
    </div>
</template>

<script>
export default {
    name: "Address",
    data() {
        return {
            // 是否加载
            isLoading: true,
            // 默认选项
            chosenAddressId: '1',
            list: [],
        }
    },
    mounted() {
        this.init()
    },
    methods: {
        async init() {
            this.isLoading = true
            let res = await this.$store.dispatch('getUserAddress')
            this.isLoading = false
            if (res.success) this.opAddress(res.data)
            else this.$myfun.resError(res.message)
        },
        // 处理数据
        opAddress(data) {
            data.forEach(item => {
                if (item.isDefault == 1) this.chosenAddressId = item.id, item.isDefault = true
                else item.isDefault = false
            });
            this.list = data
        },
        // 添加地址
        onAdd() {
            this.$router.push("/user/address/add")
        },
        // 编辑地址
        onEdit(item, index) {
            this.$router.push({
                path: '/user/address/edit',
                query: {
                    editAddress: item
                }
            })
        },
        // 改变默认地址
        async changeDefaultAddress(item, index) {
            this.$toast.fail("正在切换默认地址中")
            let res = await this.$store.dispatch('changeDefaultAddress', item.id)
            if (res.success){
                this.$toast.success(res.message)
                this.init()
            }
            else this.$myfun.resError(res.message)
        }

    },
}
</script>

<style></style>